package com.engine.salary.timer;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.biz.SalaryArchiveBiz;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.salaryarchive.dto.SalaryArchiveListDTO;
import com.engine.salary.entity.salaryarchive.param.SalaryArchiveQueryParam;
import com.engine.salary.entity.salaryarchive.po.SalaryArchivePO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesBaseInfoPO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesFundSchemePO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesOtherSchemePO;
import com.engine.salary.entity.siarchives.po.InsuranceArchivesSocialSchemePO;
import com.engine.salary.enums.salaryarchive.SalaryArchiveListTypeEnum;
import com.engine.salary.enums.salaryarchive.SalaryArchiveStatusEnum;
import com.engine.salary.enums.siaccount.EmployeeStatusEnum;
import com.engine.salary.mapper.siarchives.FundSchemeMapper;
import com.engine.salary.mapper.siarchives.OtherSchemeMapper;
import com.engine.salary.mapper.siarchives.SocialSchemeMapper;
import com.engine.salary.service.SIArchivesService;
import com.engine.salary.service.SalaryArchiveService;
import com.engine.salary.service.SalaryEmployeeService;
import com.engine.salary.service.impl.SIArchivesServiceImpl;
import com.engine.salary.service.impl.SalaryArchiveServiceImpl;
import com.engine.salary.service.impl.SalaryEmployeeServiceImpl;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Harryxzy
 * @ClassName AutoSyncInsuranceArchiveJob
 * @date 2023/08/14 9:30
 * @description 自动同步人员社保福利档案、薪资档案为公司开始日期字段（companystartdate）
 */
@Slf4j
public class AutoSyncEmpArchiveStartDateJob extends BaseCronJob {

    private String syncInsuranceArchive;
    private String syncSalaryArchive;

    private String allStayAddToPay;
    private String allGotoFixed;
    private SalaryArchiveService getSalaryArchiveService(User user) {
        return ServiceUtil.getService(SalaryArchiveServiceImpl.class, user);
    }

    private SalaryEmployeeService getSalaryEmployeeService(User user) {
        return ServiceUtil.getService(SalaryEmployeeServiceImpl.class, user);
    }


    private SIArchivesService getSIArchivesService(User user) {
        return ServiceUtil.getService(SIArchivesServiceImpl.class, user);
    }

    private SalaryArchiveBiz getSalaryArchiveMapper = new SalaryArchiveBiz();

    private SocialSchemeMapper getSocialSchemeMapper() {
        return MapperProxyFactory.getProxy(SocialSchemeMapper.class);
    }

    private FundSchemeMapper getFundSchemeMapper() {
        return MapperProxyFactory.getProxy(FundSchemeMapper.class);
    }

    private OtherSchemeMapper getOtherSchemeMapper() {
        return MapperProxyFactory.getProxy(OtherSchemeMapper.class);
    }


    @Override
    public void execute() {
        User user = new User();
        user.setUid(1);
        user.setLoginid("sysadmin");

        if (StringUtils.isBlank(syncInsuranceArchive) || !StringUtils.equals(syncInsuranceArchive, "false")) {
            // 同步社保福利档案
            // 获取社保、公积金、其他福利中起始缴纳月任意一个为空的社保档案主表po
            List<InsuranceArchivesBaseInfoPO> needSyncInsuranceBaseInfoList = getSIArchivesService(user).listStartDateIsNull(Collections.emptyList());
            // 过滤出档案状态为待增员的
            needSyncInsuranceBaseInfoList = needSyncInsuranceBaseInfoList.stream().filter(po -> po.getRunStatus().equals(EmployeeStatusEnum.STAY_ADD.getValue())).collect(Collectors.toList());
            // 获取同步人员的公司开始日期
            List<DataCollectionEmployee> employeeList = getSalaryEmployeeService(user).listByIds(SalaryEntityUtil.properties(needSyncInsuranceBaseInfoList, InsuranceArchivesBaseInfoPO::getEmployeeId, Collectors.toList()));
            Map<Long, String> empInfoMap = SalaryEntityUtil.convert2Map(employeeList, DataCollectionEmployee::getEmployeeId, emp -> {
                if (StringUtils.isBlank(emp.getCompanystartdate()) || !SalaryDateUtil.checkDay(emp.getCompanystartdate())) {
                    return "";
                } else {
                    return StringUtils.substring(emp.getCompanystartdate(), 0, 7);
                }
            });
            // 设置社保起始缴纳月信息
            List<Long> needSyncSocialArchiveIds = SalaryEntityUtil.properties(needSyncInsuranceBaseInfoList, InsuranceArchivesBaseInfoPO::getSocialArchivesId, Collectors.toList());
            List<InsuranceArchivesSocialSchemePO> insuranceArchivesSocialSchemePOS = getSIArchivesService(user).listInsuranceArchivesSocialSchemeByIds(needSyncSocialArchiveIds);
            insuranceArchivesSocialSchemePOS.stream().forEach(po -> {
                if (StringUtils.isBlank(po.getSocialStartTime()) && StringUtils.isNotBlank(empInfoMap.get(po.getEmployeeId()))) {
                    po.setSocialStartTime(empInfoMap.get(po.getEmployeeId()));
                    getSocialSchemeMapper().updateById(po);
                }
            });

            // 设置公积金起始缴纳月信息
            List<Long> needSyncFundArchiveIds = SalaryEntityUtil.properties(needSyncInsuranceBaseInfoList, InsuranceArchivesBaseInfoPO::getFundArchivesId, Collectors.toList());
            List<InsuranceArchivesFundSchemePO> insuranceArchivesFundSchemePOS = getSIArchivesService(user).listInsuranceArchivesFundSchemeByIds(needSyncFundArchiveIds);
            insuranceArchivesFundSchemePOS.stream().forEach(po -> {
                if (StringUtils.isBlank(po.getFundStartTime()) && StringUtils.isNotBlank(empInfoMap.get(po.getEmployeeId()))) {
                    po.setFundStartTime(empInfoMap.get(po.getEmployeeId()));
                    getFundSchemeMapper().updateById(po);
                }
            });

            // 设置其他福利起始缴纳月信息
            List<Long> needSyncOtherArchiveIds = SalaryEntityUtil.properties(needSyncInsuranceBaseInfoList, InsuranceArchivesBaseInfoPO::getOtherArchivesId, Collectors.toList());
            List<InsuranceArchivesOtherSchemePO> insuranceArchivesOtherSchemePOS = getSIArchivesService(user).listInsuranceArchivesOtherSchemeByIds(needSyncOtherArchiveIds);
            insuranceArchivesOtherSchemePOS.stream().forEach(po -> {
                if (StringUtils.isBlank(po.getOtherStartTime()) && StringUtils.isNotBlank(empInfoMap.get(po.getEmployeeId()))) {
                    po.setOtherStartTime(empInfoMap.get(po.getEmployeeId()));
                    getOtherSchemeMapper().updateById(po);
                }
            });
        }

        if (StringUtils.isBlank(syncSalaryArchive) || !StringUtils.equals(syncSalaryArchive, "false")) {
            // 同步薪资档案
            // 获取薪资档案起始发薪日为空且是待定薪资的档案
            List<SalaryArchivePO> salaryArchiveList = getSalaryArchiveService(user).listPayStartDateIsNull(SalaryArchiveListTypeEnum.PENDING.getValue());
            List<Long> empIds = SalaryEntityUtil.properties(salaryArchiveList, SalaryArchivePO::getEmployeeId, Collectors.toList());
            List<DataCollectionEmployee> employeeList = getSalaryEmployeeService(user).listByIds(empIds);
            Map<Long, Date> empMap = SalaryEntityUtil.convert2Map(employeeList, DataCollectionEmployee::getEmployeeId, emp -> {
                if (StringUtils.isBlank(emp.getCompanystartdate()) || !SalaryDateUtil.checkDay(emp.getCompanystartdate())) {
                    return null;
                } else {
                    return SalaryDateUtil.stringToDate(StringUtils.substring(emp.getCompanystartdate(), 0, 10));
                }
            });
            List<SalaryArchivePO> needUpdateArchiveList = salaryArchiveList.stream().filter(archive -> {
                if (archive.getPayStartDate() == null) {
                    Date startDate = empMap.get(archive.getEmployeeId());
                    if (startDate != null) {
                        archive.setPayStartDate(startDate);
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
            getSalaryArchiveMapper.batchUpdate(needUpdateArchiveList);
        }


        //一键定薪
        if (StringUtils.isNotBlank(allStayAddToPay) && !StringUtils.equals(allStayAddToPay, "false")) {
            List<InsuranceArchivesBaseInfoPO> allBaseInfoList = getSIArchivesService(user).listAll();
            List<Long> ids = allBaseInfoList.stream()
                    .filter(f -> f.getRunStatus().equals(EmployeeStatusEnum.STAY_ADD.getValue()))
                    .map(InsuranceArchivesBaseInfoPO::getId)
                    .collect(Collectors.toList());
            Map<String, Object> map = getSIArchivesService(user).stayAddToPay(ids);
            log.info("社保一键定薪结果:" + map);
        }

        if (StringUtils.isNotBlank(allGotoFixed) && !StringUtils.equals(allGotoFixed, "false")) {
            SalaryArchiveQueryParam queryParam = SalaryArchiveQueryParam.builder().build();
            queryParam.setRunStatusList(Arrays.asList(SalaryArchiveStatusEnum.PENDING.getValue()));
            List<SalaryArchiveListDTO> salaryArchiveList = getSalaryArchiveService(user).getSalaryArchiveList(queryParam);
            List<Long> ids = SalaryEntityUtil.properties(salaryArchiveList, SalaryArchiveListDTO::getId, Collectors.toList());
            Map<String, Object> map = getSalaryArchiveService(user).gotoFixed(ids);
            log.info("薪资一键定薪结果:" + map);
        }

    }

}
